﻿@namespace MudBlazor.UnitTests.TestComponents

<MudGrid>
    <MudItem xs="12">
        <MudChipSet MultiSelection="true"  Filter="true" SelectedValues="Selected" SelectedValuesChanged="SelectedChanged" Comparer="Comparer"  @bind-SelectedChips="selectedChips">
            <MudChip Text="Cappuccino" Value="@(new Coffee("cap","Cappuccino"))" />
            <MudChip Text="Cafe Latte" Value="@(new Coffee("lat","Cafe Latte"))" />
            <MudChip Text="Espresso" Value="@(new Coffee("esp","Espresso"))" />
            <MudChip Text="Irish Coffee" Value="@(new Coffee("ire","Irish Coffee"))" />
        </MudChipSet>
    </MudItem>
    <MudItem xs="12">
        <MudButton OnClick="SetSelection">Set Selection</MudButton>
    </MudItem>
    <br />
    <p class="sel">
        Selection: @(string.Join(", ", (selectedChips??new MudChip[0]).OrderBy(chip=> chip.Text).Select(chip=> chip.Text)))
    </p>
</MudGrid>

@code {
    public static string __description__ = "The comparer should be used to compare coffee objects in chipset";
    MudChip[] selectedChips;
    static CoffeeComparer Comparer { get; } = new();

    HashSet<object> Selected { get; } = new(Comparer);

    void SelectedChanged(IEnumerable<object> newSelected)
    {
        Selected.Clear();
        Selected.UnionWith(newSelected);
    }

    void SetSelection()
    {
        Selected.Clear();
        Selected.Add(new Coffee("lat", "Selected Cafe Latte"));
        Selected.Add(new Coffee("esp", "Selected Espresso"));
    }

    class Coffee
    {
        public string Key { get; set; }
        public string Name { get; set; }
        public Coffee(string key, string name) { Key = key; Name = name; }
    }

    class CoffeeComparer : IEqualityComparer<object>
    {
        public new bool Equals(object a, object b) => ((Coffee)a).Key == ((Coffee)b).Key;
        public int GetHashCode(object x) => HashCode.Combine( ((Coffee)x).Key);
    }
}

